package com.kingbook.api.filter;

import com.kingbook.core.auth.LoginManager;
import com.kingbook.core.result.JSONResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

import static com.kingbook.core.auth.LoginManager.*;

public class LoginFilter implements Filter {

    private static Logger logger = LoggerFactory.getLogger(LoginFilter.class);

    /**
     * 过滤所有需要登陆验证的url，验证登陆
     *
     * @param req
     * @param res
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String auth = request.getHeader(AUTH);
        String sign = request.getHeader(SIGN);
        String requestId = request.getHeader(REQUEST_ID);
        String uri = request.getRequestURI();
        logger.info("Header[{}] RequestURI={} sign={} Auth={} ", requestId, uri, sign, auth);

        //根据登陆uri列表 ，进行登陆验证，不在列表中的，不需要验证，并将token保存不变
//        long s = System.currentTimeMillis();
        JSONResult re = LoginManager.checkLogin(requestId, sign, auth);
//        logger.info("[{}] checkLogin spend seconds : {}ms ", requestId, System.currentTimeMillis() - s);
        if (re.isSuccess()) {
            response.setHeader(AUTH, re.getMsg());
            chain.doFilter(req, res);
        } else {
            logger.warn("Header[{}]: RequestURI={} Msg={} - return 301", requestId, uri, re.getMsg());
            response.setStatus(301);
            PrintWriter out = response.getWriter();        //创建一个输出流
            out.print("");      //如果为空则通过javaScript脚本出输出提示并跳转到index.jsp页面
        }
    }

    public void init(FilterConfig filterConfig) {
    }

    public void destroy() {
    }
}
